package pl.edu.agh.sius.model;

import java.util.HashMap;
import java.util.Map;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;

import pl.edu.agh.sius.controller.InputFileController;

public class MailBuilder {

	// should remain static
	private static Map<String, String> headers = new HashMap<String, String>();

	static {
		headers.put("name", "Imię: ");
		headers.put("surname", "Nazwisko: ");
		headers.put("pesel", "Pesel: ");
		headers.put("address", "Adres: ");
		headers.put("cadastre", "Lokalizacja dokumentu \""
				+ EstateSplitRequestBB.CADASTRE + "\": ");
		headers.put("estateSplitPetition", "Lokalizacja dokumentu \""
				+ EstateSplitRequestBB.ESTATE_SPLIT_PETITION + "\": ");
		headers.put("localSpatialPlan", "Lokalizacja dokumentu \""
				+ EstateSplitRequestBB.LOCAL_SPATIAL_PLAN + "\": ");
		headers.put("propertyOwnership", "Lokalizacja dokumentu \""
				+ EstateSplitRequestBB.PROPERTY_OWNERSHIP + "\": ");

		headers.put("statementOfEarnings", "Lokalizacja dokumentu \""
				+ TemporaryBenefitRequestBB.STATEMENT_OF_EARNINGS + "\": ");
		headers.put("temporalBenefitPetition", "Lokalizacja dokumentu \""
				+ TemporaryBenefitRequestBB.TEMPORAL_BENEFIT_PETITION + "\": ");

		headers.put("financialGuarantees", "Lokalizacja dokumentu \""
				+ WasteTransportRequestBB.FINANCIAL_GRUARANEES + "\": ");
		headers
				.put(
						"wasteTransportPermissionPetition",
						"Lokalizacja dokumentu \""
								+ WasteTransportRequestBB.WASTE_TRANSPORT_PERMISSION_PETITION
								+ "\": ");
	}

	private static String extractValue(String text, String key) {
		if (text == null || key == null) {
			return null;
		}
		int start = text.indexOf(key) + key.length();
		int end = text.indexOf("\n", start);
		return text.substring(start, end);
	}

	public static com.intalio.bpms.firstprocess.time.EstateSplitRequest buildEstateSplitRequestFromMail(
			String s) {
		com.intalio.bpms.firstprocess.time.EstateSplitRequest esr = new com.intalio.bpms.firstprocess.time.EstateSplitRequest();
		esr.setAddress(extractValue(s, headers.get("address")));
		esr.setCadastreDocURL(extractValue(s, headers.get("cadastre")));
		esr.setEstateSplitPetitionDocURL(extractValue(s, headers
				.get("estateSplitPetition")));
		esr.setFirstName(extractValue(s, headers.get("name")));
		esr.setLocalSpatialPlanDocURL(extractValue(s, headers
				.get("localSpatialPlan")));
		esr.setPesel(extractValue(s, headers.get("pesel")));
		esr.setPropertyOwnershipDocURL(extractValue(s, headers
				.get("propertyOwnership")));
		esr.setSurname(extractValue(s, headers.get("surname")));
		return esr;
	}

	public static pl.edu.agh.siusbox.tempbenefit.schema.TemporaryBenefitRequest buildTemporaryBenefitRequestFromMail(
			String s) {
		pl.edu.agh.siusbox.tempbenefit.schema.TemporaryBenefitRequest esr = new pl.edu.agh.siusbox.tempbenefit.schema.TemporaryBenefitRequest();
		esr.setAddress(extractValue(s, headers.get("address")));
		esr.setFirstName(extractValue(s, headers.get("name")));
		esr.setPesel(extractValue(s, headers.get("pesel")));
		esr.setSurname(extractValue(s, headers.get("surname")));
		esr.setStatementOfEarningsDocURL(extractValue(s, headers
				.get("statementOfEarnings")));
		esr.setTempBenefitPetitionDocURL(extractValue(s, headers
				.get("temporalBenefitPetition")));
		return esr;
	}

	public static pl.edu.agh.siusbox.wastetransport.schema.WasteTransportRequest buildWasteTransportRequestFromMail(
			String s) {
		pl.edu.agh.siusbox.wastetransport.schema.WasteTransportRequest esr = new pl.edu.agh.siusbox.wastetransport.schema.WasteTransportRequest();
		esr.setAddress(extractValue(s, headers.get("address")));
		esr.setFirstName(extractValue(s, headers.get("name")));
		esr.setPesel(extractValue(s, headers.get("pesel")));
		esr.setSurname(extractValue(s, headers.get("surname")));
		esr.setFinancialGuaranteesDocURL(extractValue(s, headers
				.get("financialGuarantees")));
		esr.setWasteTransportPermissionPetitionDocURL(extractValue(s, headers
				.get("wasteTransportPermissionPetition")));
		return esr;
	}

	protected static void addAttachements(MimeMultipart mp,
			InputFileController ifc, String textContent)
			throws MessagingException {
		MimeBodyPart mbp = new MimeBodyPart();
		mbp.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
		mbp.setHeader("Content-Transfer-Encoding", "quoted-printable");
		mbp.setText(textContent, "utf-8");
		mp.addBodyPart(mbp, 0);

		for (InputFileData ifd : ifc.getFileList()) {
			mbp = new MimeBodyPart();
			FileDataSource fds = new FileDataSource(ifd.getFileInfo().getFile());
			mbp.setDataHandler(new DataHandler(fds));
			mbp.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
			mbp.setHeader("Content-Transfer-Encoding", "quoted-printable");
			mbp.setFileName("[" + ifd.getFileFormalName() + "] "
					+ fds.getName());
			mp.addBodyPart(mbp);
		}
	}

	protected static MimeMultipart buildMailFromTemporaryBenefitRequest(
			TemporaryBenefitRequestBB concern, InputFileController ifc)
			throws MessagingException {

		MimeMultipart mp = new MimeMultipart();

		StringBuilder sb = new StringBuilder();
		sb.append("Rodzaj sprawy: Podanie o podział nieruchomości.\n");
		sb.append(headers.get("name") + concern.getFirstName() + "\n");
		sb.append(headers.get("surname") + concern.getSurname() + "\n");
		sb.append(headers.get("pesel") + concern.getPesel() + "\n");
		sb.append(headers.get("address") + concern.getAddress() + "\n");

		sb.append(headers.get("statementOfEarnings")
				+ concern.getStatementOfEarningsDocURL() + "\n");
		sb.append(headers.get("temporalBenefitPetition")
				+ concern.getTempBenefitPetitionDocURL() + "\n");

		addAttachements(mp, ifc, sb.toString());
		return mp;
	}

	protected static MimeMultipart buildMailFromWasteTransportRequest(
			WasteTransportRequestBB concern, InputFileController ifc)
			throws MessagingException {

		MimeMultipart mp = new MimeMultipart();

		StringBuilder sb = new StringBuilder();
		sb.append("Rodzaj sprawy: Podanie o podział nieruchomości.\n");
		sb.append(headers.get("name") + concern.getFirstName() + "\n");
		sb.append(headers.get("surname") + concern.getSurname() + "\n");
		sb.append(headers.get("pesel") + concern.getPesel() + "\n");
		sb.append(headers.get("address") + concern.getAddress() + "\n");

		sb.append(headers.get("financialGuarantees")
				+ concern.getFinancialGuaranteesDocURL() + "\n");
		sb.append(headers.get("wasteTransportPermissionPetition")
				+ concern.getWasteTransportPermissionPetitionDocURL() + "\n");

		addAttachements(mp, ifc, sb.toString());
		return mp;
	}

	protected static MimeMultipart buildMailFromEstateSplitRequest(
			EstateSplitRequestBB concern, InputFileController ifc)
			throws MessagingException {

		MimeMultipart mp = new MimeMultipart();

		StringBuilder sb = new StringBuilder();
		sb.append("Rodzaj sprawy: Podanie o podział nieruchomości.\n");
		sb.append(headers.get("name") + concern.getFirstName() + "\n");
		sb.append(headers.get("surname") + concern.getSurname() + "\n");
		sb.append(headers.get("pesel") + concern.getPesel() + "\n");
		sb.append(headers.get("address") + concern.getAddress() + "\n");

		sb.append(headers.get("cadastre") + concern.getCadastreDocURL() + "\n");
		sb.append(headers.get("estateSplitPetition")
				+ concern.getEstateSplitPetitionDocURL() + "\n");
		sb.append(headers.get("localSpatialPlan")
				+ concern.getLocalSpatialPlanDocURL() + "\n");
		sb.append(headers.get("propertyOwnership")
				+ concern.getPropertyOwnershipDocURL() + "\n");

		addAttachements(mp, ifc, sb.toString());
		return mp;
	}

	public static MimeMultipart buildMail(ConcernBB concern,
			InputFileController ifc) throws MessagingException {
		if (concern instanceof EstateSplitRequestBB) {
			return buildMailFromEstateSplitRequest(
					(EstateSplitRequestBB) concern, ifc);
		}
		if (concern instanceof TemporaryBenefitRequestBB) {
			return buildMailFromTemporaryBenefitRequest(
					(TemporaryBenefitRequestBB) concern, ifc);
		}
		if (concern instanceof WasteTransportRequestBB) {
			return buildMailFromWasteTransportRequest(
					(WasteTransportRequestBB) concern, ifc);
		}
		return null;
	}

}
